// src/api/index.js
import axios from 'axios'
import { getCookie } from '@/utils/cookie'

// 创建 axios 实例
const api = axios.create({
  baseURL: 'http://10.115.0.71:8080/api', // 后端接口基础地址
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: true,
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 添加 token 等认证信息
    const token = getCookie('userToken')
    const key = getCookie('key')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
      config.headers.key = key
    }

    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    if (response.config.responseType === 'blob') {
      return response
    }
    return response.data
  },
  (error) => {
    console.error('API Error:', error)
    return Promise.reject(error)
  },
)

export default api
